﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using seejee_Backendium.Core.Interfaces;
using seejee_Backendium.Data.DbContest;
using seejee_Backendium.Data.Services;

namespace seejee_Backendium.WEB.Controllers
{
    [ApiController]
    [EnableCors("AllowVueApp")]
    [Route("api/[controller]")]
    public class APKController : ControllerBase
    {
        private readonly ILogger<APKController> _logger;
        private readonly string _uploadDirectory;
        private readonly IApkService _apkService;
        private readonly string _customBaseUrl;
        private const int MaxFileSize = 100 * 1024 * 1024; // 100MB
        //private readonly string _customBaseUrl = "http://192.168.0.194:5006"; // 这里换成你的实际IP

        public APKController(ILogger<APKController> logger, IApkService apkService, IConfiguration configuration)
        {
            _logger = logger;
            _apkService = apkService;
            _customBaseUrl = configuration["AppSettings:ApiBaseUrl"];   
            _uploadDirectory = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Uploads", "APKs");

            if (!Directory.Exists(_uploadDirectory))
            {
                Directory.CreateDirectory(_uploadDirectory);
            }
        }

        [HttpPost("upload")]
        [HttpGet]
        [DisableRequestSizeLimit] // 禁用默认大小限制
        [RequestFormLimits(MultipartBodyLengthLimit = 100_000_000)] // 100MB
        public async Task<IActionResult> UploadAPK([FromForm] IFormFile file)
        {
            try
            {
                // 验证文件
                if (file == null || file.Length == 0)
                {
                    return BadRequest(ApiResponse.Fail("请选择有效的APK文件"));
                }

                if (file.Length > MaxFileSize)
                {
                    return BadRequest(ApiResponse.Fail("文件大小不能超过100MB"));
                }

                var extension = Path.GetExtension(file.FileName).ToLower();
                if (extension != ".apk")
                {
                    return BadRequest(ApiResponse.Fail("只能上传APK文件"));
                }

                // 获取安全的原始文件名
                var originalFileName = Path.GetFileName(file.FileName);
                // 替换可能的问题字符
                var safeFileName = string.Join("_", originalFileName.Split(Path.GetInvalidFileNameChars()));
                // 组合唯一前缀和原始文件名
                var fileName = $"{Guid.NewGuid().ToString("N").Substring(0, 8)}_{safeFileName}";
                // 获取文件路径
                var filePath = Path.Combine(_uploadDirectory, fileName);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 提取APK信息（实际项目中应使用AndroidAssetStudio等工具）
                var appName = Path.GetFileNameWithoutExtension(file.FileName);
                var packageName = $"com.custom.{appName.ToLower().Replace(" ", "")}";

                // 生成下载URL
                var downloadUrl = $"{_customBaseUrl}/api/apk/download/{fileName}";

                return Ok(ApiResponse.Success1(new
                {
                    appName,
                    packageName,
                    downloadUrl,
                    fileSize = file.Length,
                    uploadTime = DateTime.Now
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "APK上传失败");
                return StatusCode(500, ApiResponse.Fail("APK上传失败"));
            }
        }

        [HttpGet("download/{fileName}")]
        public IActionResult Download(string fileName)
        {
            try
            {
                var filePath = Path.Combine(_uploadDirectory, fileName);
                if (!System.IO.File.Exists(filePath))
                {
                    return NotFound(ApiResponse.Fail("文件不存在"));
                }

                // 提取原始文件名（去掉GUID前缀）
                string displayName = fileName.Contains("_")
                    ? fileName.Split(new[] { '_' }, 2)[1]
                    : fileName;

                // 返回文件流，并指定下载显示名称
                var fileStream = System.IO.File.OpenRead(filePath);
                return File(fileStream, "application/vnd.android.package-archive", WebUtility.UrlDecode(displayName));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "文件下载失败");
                return StatusCode(500, ApiResponse.Fail("文件下载失败"));
            }
        }

        [HttpGet("apps")]
        public IActionResult GetAppList([FromQuery] int page = 1, [FromQuery] int size = 10)
        {
            try
            {
                // 实际项目中应从数据库获取
                var mockData = Enumerable.Range(1, 50).Select(i => new
                {
                    id = i,
                    userName = $"客户{i}",
                    appName = $"应用{i}",
                    packageName = $"com.example.app{i}",
                    downloadUrl = $"{_customBaseUrl}/api/apk/download/app{i}.apk",
                    uploadTime = DateTime.Now.AddDays(-i)
                }).ToList();

                var pagedData = mockData
                    .Skip((page - 1) * size)
                    .Take(size)
                    .ToList();

                return Ok(ApiResponse.Success1(new
                {
                    items = pagedData,
                    total = mockData.Count
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取应用列表失败");
                return StatusCode(500, ApiResponse.Fail("获取应用列表失败"));
            }
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteAPK(int id)
        {
            try
            {

                // 2. 获取文件地址
                var appAddress = await _apkService.GetPassByUserNameAsync(id);

                if (string.IsNullOrEmpty(appAddress))
                {
                    return NotFound(new ProblemDetails
                    {
                        Title = "APK地址不存在",
                        Detail = $"用户 {id} 没有关联的APK地址",
                        Status = StatusCodes.Status404NotFound
                    });
                }

                // 3. 验证地址格式
                if (!Uri.TryCreate(appAddress, UriKind.Absolute, out var uri))
                {
                    return BadRequest(new ProblemDetails
                    {
                        Title = "无效的文件地址",
                        Detail = $"地址格式不正确: {appAddress}",
                        Status = StatusCodes.Status400BadRequest
                    });
                }

                // 4. 获取本地文件路径
                var localFilePath = uri.IsFile ? uri.LocalPath : Path.Combine(_uploadDirectory, Path.GetFileName(uri.LocalPath));

                // 5. 检查文件是否存在
                if (!System.IO.File.Exists(localFilePath))
                {
                    return NotFound(new ProblemDetails
                    {
                        Title = "APK文件不存在",
                        Detail = $"找不到文件: {localFilePath}",
                        Status = StatusCodes.Status404NotFound
                    });
                }

                // 6. 删除文件
                System.IO.File.Delete(localFilePath);
                _logger.LogInformation($"已删除文件: {localFilePath}");

                // 7. 更新数据库记录（可选）
                // await _apkService.ClearAppAddressAsync(userName);

                return NoContent(); // 204 No Content
            }
            catch (UnauthorizedAccessException ex)
            {
                _logger.LogError(ex, "没有权限删除文件");
                return StatusCode(403, new ProblemDetails
                {
                    Title = "权限不足",
                    Detail = "没有权限删除该文件",
                    Status = StatusCodes.Status403Forbidden
                });
            }
            catch (IOException ex)
            {
                _logger.LogError(ex, "文件操作失败");
                return StatusCode(500, new ProblemDetails
                {
                    Title = "文件操作错误",
                    Detail = "处理文件时发生错误",
                    Status = StatusCodes.Status500InternalServerError
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除APK文件失败");
                return StatusCode(500, new ProblemDetails
                {
                    Title = "服务器错误",
                    Detail = "删除APK文件时发生内部错误",
                    Status = StatusCodes.Status500InternalServerError
                });
            }
        }

        public class ApiResponse
        {
            public bool Success { get; set; }
            public string Message { get; set; }
            public object Data { get; set; }

            public static ApiResponse Success1(object data = null, string message = "操作成功")
            {
                return new ApiResponse
                {
                    Success = true,
                    Message = message,
                    Data = data
                };
            }

            public static ApiResponse Fail(string message, object data = null)
            {
                return new ApiResponse
                {
                    Success = false,
                    Message = message,
                    Data = data
                };
            }
        }
    }
}